"""
@author: 江同学呀
@file:  enum_utils.py
@date: 2025/3/12 21:40
@desc: 
    
"""
import enum
from typing import Union, List, TypeVar, Generic

from espc.err import ESPCInvalidTypeError


# 定义一个类型变量，表示 EnumBase 或其子类
T = TypeVar('T', bound='EnumBase')


class EnumBase(enum.Enum):
    """
    枚举类工具
    """

    @classmethod
    def exists(cls, value: Union[int, str]):
        """
        是否存在值
        :param value:
        :return:
        """
        try:
            cls(value)
            return True
        except Exception:
            return False

    @classmethod
    def exists_key(cls, key: Union[int, str]):
        """
        是否存在key
        :param key:
        :return:
        """
        try:
            member = cls[key]
            return True
        except Exception:
            return False

    @classmethod
    def keys(cls) -> List[str]:
        """
        所有键
        :return:
        """
        return [item.name for item in cls]

    @classmethod
    def values(cls) -> List:
        """
        所有值
        :return:
        """
        return [item.value for item in cls]

    def __or__(self, other: Union["EnumBase", "EnumMerge"]) -> "EnumMerge":
        if isinstance(other, EnumBase):
            return EnumMerge(self) | other
        elif isinstance(other, EnumMerge):
            other |= other._enums
            return other
        else:
            raise ESPCInvalidTypeError("不支持该类型")


class EnumMerge(Generic[T]):
    """
    枚举类合并
    """
    def __init__(self, enums: EnumBase):
        self._enums: List[EnumBase[T]] = [enums]
        return

    def __or__(self, other: Union[T, "EnumBase[T]"]) -> "EnumMerge[T]":
        if isinstance(other, EnumMerge):
            self._enums.extend(other._enums)
        else:
            self._enums.append(other)
        return self

    def __iter__(self):
        return iter(self._enums)

    def __len__(self):
        return len(self._enums)

    def __str__(self):
        return "|".join(item.value for item in self._enums)

